import React, { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Plus, Search, AlertTriangle, Upload } from "lucide-react";
import SafetyRiskPointCard from "./SafetyRiskPointCard";
import SafetyRiskPointForm from "./SafetyRiskPointForm";
import SafetyRiskPointImportModal from './SafetyRiskPointImportModal';

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
export default function SafetyRiskPointManager({
  riskPoints,
  onSave,
  onDelete,
  isLoading,
  onFilteredCountChange,
  onRefreshData
}) {
  const [showForm, setShowForm] = useState(false);
  const [editingRisk, setEditingRisk] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");
  const [showImportModal, setShowImportModal] = useState(false);

  // 优化分类数据获取，确保正确提取primaryCategory
  const categories = useMemo(() => {
    // 从风险点中提取所有非空的primaryCategory并去重
    const uniqueCategories = [
      ...new Set(riskPoints.map((r) => r.primaryCategory).filter(Boolean)),
    ];
    // 按名称排序，提升用户体验
    return uniqueCategories.sort((a, b) => a.localeCompare(b));
  }, [riskPoints]);

  const handleEdit = (risk) => {
    setEditingRisk(risk);
    setShowForm(true);
    setTimeout(() => {
      const formElement = document.getElementById("emergency-measure-form");
      console.log(formElement, "formElement");

      if (formElement) {
        formElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 500);
  };

  const handleCancel = () => {
    setEditingRisk(null);
    setShowForm(false);
  };

  const handleSubmit = async (data) => {
    await onSave(editingRisk ? { ...data, id: editingRisk.id } : data);
    handleCancel();
  };

  // 优化筛选逻辑，使用useMemo缓存结果避免重复计算
  const filteredRisks = useMemo(() => {
    return riskPoints.filter((risk) => {
      // 搜索词匹配：描述或编码
      const termMatch =
        !searchTerm ||
        risk.riskDescription.toLowerCase().includes(searchTerm.toLowerCase()) ||
        risk.riskCode.toLowerCase().includes(searchTerm.toLowerCase());

      // 分类匹配：修复原代码的字段错误（category -> primaryCategory）
      const categoryMatch =
        filterCategory === "all" || risk.primaryCategory === filterCategory;

      return termMatch && categoryMatch;
    });
  }, [riskPoints, searchTerm, filterCategory]);

  useEffect(() => {
    if (onFilteredCountChange) {
      onFilteredCountChange(filteredRisks.length);
    }
  }, [filteredRisks.length, onFilteredCountChange]);

  // 5. 优化计数更新逻辑
  useEffect(() => {
    onFilteredCountChange?.(filteredRisks.length);
  }, [filteredRisks.length, onFilteredCountChange]);

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <Search
            className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"
            onClick={() => {
              console.log(categories, "categoriescategories");
            }}
          />
          <Input
            placeholder="搜索危险点描述或编码..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
            suffix={
              searchTerm && (
                <button
                  onClick={() => setSearchTerm("")}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ×
                </button>
              )
            }
          />
        </div>
        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-full md:w-[180px]">
            <SelectValue placeholder="所有类别" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">所有类别</SelectItem>
            {categories.map((cat) => (
              <SelectItem key={cat} value={cat}>
                {cat}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Button onClick={() => setShowImportModal(true)} variant="outline">
          <Upload className="w-4 h-4 mr-2" />
          批量导入
        </Button>
        <Button
          onClick={() => {
            setEditingRisk(null);
            setShowForm(true);
          }}
          className="bg-purple-600 hover:bg-purple-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          新建危险点
        </Button>
      </div>

      {showImportModal && (
        <SafetyRiskPointImportModal
          isOpen={showImportModal}
          onClose={() => setShowImportModal(false)}
          onImportSuccess={() => {
            setShowImportModal(false);
            if (onRefreshData) {
              onRefreshData();
            }
          }}
        />
      )}
      {/* 导入危险点 */}
      {showForm && (
        <SafetyRiskPointForm
          riskPoint={editingRisk}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}

      {isLoading ? (
        <div className="text-center p-8">加载中...</div>
      ) : filteredRisks.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredRisks.map((risk) => (
            <SafetyRiskPointCard
              key={risk.id}
              riskPoint={risk}
              onEdit={handleEdit}
              onDelete={onDelete}
            />
          ))}
        </div>
      ) : (
        <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200">
          <AlertTriangle className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">暂无匹配的危险点</p>
          <p>尝试调整搜索条件或创建新的危险点</p>
        </div>
      )}
    </div>
  );
}
